require('./bootstrap');
import Vue from 'vue';
import App from './App.vue'
import router from './router'
import store from './store'
import VueCookie from 'vue-cookie';
import ElementUI from 'element-ui';
import NProgress from 'nprogress' // Progress 进度条
import Moment from 'moment';
import 'element-ui/lib/theme-chalk/index.css';
import 'font-awesome/css/font-awesome.css';
import '../css/admin.css';
// import '../css/reset.css';
import 'nprogress/nprogress.css'// Progress 进度条样式

Vue.use(ElementUI);
Vue.use(VueCookie);

Vue.prototype.$store = store;
Vue.prototype.moment = Moment;

router.beforeEach((to, from, next) => {
    NProgress.start();//开启进度条
    if (to.meta.title){
        document.title = '管理系统-' + to.meta.title;//动态化每个页面的标题
    }
    store.dispatch('setMetaName', to.meta.title);
    store.dispatch('setActive', to.path);
    const whiteList = ['Login'];
    const token = VueCookie.get('token');
    if (token) {
        //如果令牌存在，不能直接访问登录界面
        if (to.matched.some(m => m.meta.login)) {
            next({name: 'Main'});
        } else {
            //动态路由只挂载一次
            if (store.getters.routers.length) {
                next();
            } else {
                store.dispatch('generateRoutes').then(() => {
                    router.addRoutes(store.getters.routers); // 动态添加可访问路由表
                    console.log(store.getters.routers)
                    next({...to});//hack方法 确保addRoutes已完成
                });
            }
        }
    } else {
        //登录白名单，在执行next({name:'Login'})的时候允许进入该页面
        if (whiteList.includes(to.name)) {
            next();
        } else {
            next({name: 'Login'});// token不存在的情况全部重定向到登录页
        }
    }
});

// NProgress.configure({ showSpinner: false });//取消右上角的进度环
router.afterEach((transition) => {
    NProgress.done();//关闭进度条
});

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');
